<template>
  <div>
    <el-row>
      <el-col :span="24">Ariana Grande 《one last time》</el-col>
    </el-row>
    <el-row>
      <form action="#" @submit.prevent="getIssues">
        <el-col :span="10">
          <el-input v-model="repository" placeholder="owner/repo Name"></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="getIssues">query</el-button>
        </el-col>
      </form>
    </el-row>
    <el-row>
      <el-col :span="20">
        <charts-d3 :issues="issues"></charts-d3>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "axios";
import moment from "moment";
import ChartsD3 from "./ChartsD3";
import { data } from "@/common/facebook";
export default {
  components: { ChartsD3 },
  data() {
    return {
      repository: "",
      issues: [],
      startDate: null
    };
  },
  methods: {
    getDateRange() {
      const startDate = moment().subtract(6, "days");
      const endDate = moment();
      const dates = [];

      while (startDate.isSameOrBefore(endDate)) {
        dates.push({
          day: startDate.format("MMM DD YY"),
          issues: 0
        });

        startDate.add(1, "days");
      }

      return dates;
    },
    async getIssues() {
      this.startDate = moment()
        .subtract(6, "days")
        .format("YYYY-MM-DD");

      let ret;
      try {
        const res = await axios.get(
          `https://api.github.com/search/issues?q=repo:${this.repository}+is:issue+is:open+created:>=${this.startDate}`,
          { params: { per_page: 100 } }
        );
        ret = [res, null];
      } catch (e) {
        console.log(e);
        ret = [data, e];
      }

      const response = ret[1] !== null ? ret[0] : ret[0].data;
      console.log(response);
      const payload = this.getDateRange();

      response.items.forEach(item => {
        const key = moment(item.created_at).format("MMM DD YY");
        const obj = payload.filter(o => o.day === key)[0];
        obj.issues += 1;
      });

      this.issues = payload;
      console.log(this.issues);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>